package com.demo.index;

import java.util.Date;
import java.util.List;

import com.demo.common.constant.ConstantDtoFlight;
import com.demo.common.model.Flightinfo;
import com.demo.common.model.Flightno;
import com.demo.common.model.Flighttrends;
import com.demo.common.model.Proxyip;
import com.demo.common.tool.ToolTime;
import com.demo.flightInfo.FlightSearchValidator;
import com.demo.webmagic.dto.DtoFlightInfo;
import com.demo.webmagic.pageProcessor.PageProcessorHanglvzongheng;
import com.demo.webmagic.pageProcessor.PageProcessorVeryZhunFlighInfo;
import com.demo.webmagic.pipeline.PipelineVeryZhunFlightInfo;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.ehcache.CacheKit;

import us.codecraft.webmagic.Spider;

/**
 * IndexController
 */
public class IndexController extends Controller {
	
	private static final Log log = Log.getLog(IndexController.class);
	
	public void index() {
		render("index.html");
	}
	
	@Before(FlightSearchValidator.class)
	public void search() {
		// 1.获取航班号
		String fno = getPara("fno");
		String searchDate = getPara("searchDate");
		if(StrKit.isBlank(searchDate)) 
			searchDate = ToolTime.getNowTimeStr("yyyy-MM-dd");
		// 2.转大写
		fno = fno.toUpperCase();
		// 3.根据fno和当天的时间生成key
		String key = fno + "#" + searchDate;
		// 4.通过key从缓存中获取数据
		DtoFlightInfo result = CacheKit.get("flight", key);
		// 5.判断数据是否存在
		if (result == null) {
			result = Flightinfo.dao.getByFno(fno, searchDate);
			if (result == null) {
				// 5.1如果不存在，则通过http请求获取数据
				log.debug("缓存中不存在数据，通过http访问获取数据");
				try {
					result = getFlightInfoFromWeb(fno, searchDate);
					CacheKit.put("flight", key, result);
				} catch (Exception e) {
					log.error(e.getMessage());
					result = new DtoFlightInfo();
					result.setCode(ConstantDtoFlight.code_fail);
					result.setMessage(ConstantDtoFlight.message_fno_fail);
				}
			} else {
				CacheKit.put("flight", key, result);
				setAttr("result", result);
				render("/index/index.html");
				return;
			}
		} else {
			// 5.2如果缓存中有数据，则分析是否需要通过http请求数据
			if (ToolTime.getIntervalMinute(result.getSearchTime(), new Date()) > ConstantDtoFlight.polling_interval) {
				List<Flighttrends> trendsList = result.getTrendsList();
				boolean flag = true;
				for (Flighttrends flighttrends : trendsList) {
					String flightStatus = flighttrends.getFlightStatus();
					if (!"已经到达".equals(flightStatus) && !"已经取消".equals(flightStatus)) {
						flag = false;
						break;
					}
				}
				if (flag) {
					result.setEnd(true);
					CacheKit.put("flight", key, result);
				} else {
					log.debug("缓存中不存在数据，通过http访问获取数据");
					try {
						result = getFlightInfoFromWeb(fno, searchDate);
						CacheKit.put("flight", key, result);
					} catch (Exception e) {
						log.error(e.getMessage());
						result = new DtoFlightInfo();
						result.setCode(ConstantDtoFlight.code_fail);
						result.setMessage(ConstantDtoFlight.message_fno_fail);
					}
				}
			}
		}
		// 返回json数据
		setAttr("result", result);
		setAttr("fno", fno);
		setAttr("searchDate", searchDate);
		render("/index/index.html");
	}
	
	private DtoFlightInfo getFlightInfoFromWeb(String fno, String searchDate) throws Exception {
		if(searchDate.equals(ToolTime.getNowTimeStr("yyyy-MM-dd"))) {
			return getFlightInfoByVeryZhun(fno);
		} else {
			return getFlightInfoByHangLvZongHeng(fno, searchDate);
		}
	}
	
	private DtoFlightInfo getFlightInfoByVeryZhun(String fno) throws Exception {
		DtoFlightInfo result;
		String url = "http://www.veryzhun.com/searchnum2.asp?flightnum=" + fno;
		PageProcessorVeryZhunFlighInfo veryZhunFlighInfo = new PageProcessorVeryZhunFlighInfo(
				Proxyip.dao.getValiProxyip());
		Spider.create(veryZhunFlighInfo).addUrl(url).addPipeline(new PipelineVeryZhunFlightInfo()).run();
		result = veryZhunFlighInfo.getDtoFlightInfo();
		result.setSearchTime(new Date());
		if (result.getFlightInfo() != null) {
			Flightno flightno = Flightno.dao.findFirst("SELECT * FROM flightno WHERE fno = ?", fno);
			if (flightno == null) {
				flightno = new Flightno();
				flightno.setFno(fno);
				flightno.save();
			}
		}
		return result;
	}
	
	private DtoFlightInfo getFlightInfoByHangLvZongHeng(String fno, String searchDate) throws Exception {
		DtoFlightInfo result;
		String url = "http://www.umetrip.com/mskyweb/fs/fc.do?flightNo=@fno@&date=@date@&channel=";
		url = url.replace("@fno@", fno);
		url = url.replace("@date@", searchDate);
		PageProcessorHanglvzongheng hanglvzongheng = new PageProcessorHanglvzongheng(Proxyip.dao.getValiProxyip());
		//String url = "http://www.veryzhun.com/searchnum2.asp?flightnum=" + fno;
		Spider.create(hanglvzongheng).addUrl(url).addPipeline(new PipelineVeryZhunFlightInfo()).run();
		result = hanglvzongheng.getDtoFlightInfo();
		result.setSearchTime(new Date());
		result.setEnd(true);
		if (result.getFlightInfo() != null) {
			Flightno flightno = Flightno.dao.findFirst("SELECT * FROM flightno WHERE fno = ?", fno);
			if (flightno == null) {
				flightno = new Flightno();
				flightno.setFno(fno);
				flightno.save();
			}
		}
		return result;
	}
}





